import queryString from "query-string";
import Taro from '@tarojs/taro'
import {showToast} from "./app_tool";
import {Token, UserId} from "../constants/enum_consts";

const METHOD_GET = 'GET';
const METHOD_DELETE = 'DELETE';
const METHOD_POST = 'POST';
const METHOD_PUT = 'PUT';
const TRY_AGAIN_COUNT = 0;

let SHOW_LOADING_TAG = true;
const requestApi = (cfg, tryAgainCount = TRY_AGAIN_COUNT, showLoading = true) => {
    if (showLoading) {
        showLoadingTime();
    }
    let header = Object.assign({}, cfg.header, {
        token:  Taro.getStorageSync(Token),
    });
    let config = {
        ...cfg,
        header,
    };
    return Taro.request(config).then(res => {
        if (res.statusCode === 200) {
            SHOW_LOADING_TAG = false;
            Taro.hideLoading();
            return res.data
        } else {
            if (tryAgainCount) {
                return requestApi(cfg, tryAgainCount - 1)
            } else {
                showToast('数据异常,请刷新页面')
            }
            Taro.hideLoading();
        }
    }).catch((e) => {
        if (tryAgainCount) {
            return requestApi(cfg, tryAgainCount - 1)
        } else {
            showToast('数据异常,请刷新页面')
        }
        Taro.hideLoading();
    })
};

export const getApi = (url, params) => {
    let thisParams = {...params};
    // if (!thisParams._timestamp) {
    //     thisParams._timestamp = Date.now()
    // }
    let newParams = publicParam(thisParams);
    let requestUrl = genUrl(url, newParams)
    let config = {
        method: METHOD_GET,
        url: requestUrl,
    }
    return requestApi(config, TRY_AGAIN_COUNT, !params.current)
}

const genUrl = (url, params) => {
    let paramsStr = queryString.stringify(params)
    let splitChar = url.indexOf('?') === -1 ? '?' : '&'
    return url + splitChar + paramsStr
}

export const postApi = (url, thisParams) => {
    let newParams = publicParam(thisParams);
    let config = {
        method: METHOD_POST,
        header: {
            'Content-Type': 'application/json',
        },
        data: newParams,
        url: url
    }
    return requestApi(config, TRY_AGAIN_COUNT)
}

export const putApi = (url, thisParams) => {
    let newParams = publicParam(thisParams);
    let config = {
        method: METHOD_PUT,
        header: {
            'Content-Type': 'application/json',
        },
        data: newParams,
        url: url
    }
    return requestApi(config, TRY_AGAIN_COUNT)
}

export const deleteApi = (url, params) => {
    let thisParams = {...params};
    let newParams = publicParam(thisParams);
    let requestUrl = genUrl(url, newParams)
    let config = {
        method: METHOD_DELETE,
        url: requestUrl,
    };
    return requestApi(config, TRY_AGAIN_COUNT, !params.current)
};

export const postFormApi = (url, thisParams) => {
    let newParams = publicParam(thisParams);
    let config = {
        method: METHOD_POST,
        header: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        data: encodeParam(newParams),
        url: url
    }
    return requestApi(config, TRY_AGAIN_COUNT)
}

const encodeParam = (params) => {
    let paramArr = []
    Object.keys(params).forEach((key) => {
        if (typeof params[key] !== 'undefined') {
            paramArr.push(key + '=' + encodeURIComponent(params[key]))
        }
    })
    return paramArr.join('&')
}

const publicParam = (thisParams) => {
    // if (Taro.getStorageSync(Token)) {
    //     let token = Taro.getStorageSync(Token);
    //     let userId = Taro.getStorageSync(UserId);
    //     let newParams = {...thisParams};
    //     newParams.userId = userId
    //     return newParams
    // }
    return thisParams
}

const showLoadingTime = () => {
    SHOW_LOADING_TAG = true;
    setTimeout(function () {
        if (SHOW_LOADING_TAG) {
            Taro.showLoading({
                title: '加载中...',
                mask: true,
                success: function () {
                    setTimeout(function () {
                        Taro.hideLoading();
                    }, 30000);
                }
            });
        }
    }, 300);
}
